package Test.限流算法;

/**
 * @Author: kirito
 * @Date: 2025/3/11 20:19
 * @Description:
 * 一个容量为capacity的令牌桶，起一个线程以以恒定速率rate放令牌
 * 放令牌的时候判断与容量的关系  注意令牌满
 * 当前令牌数为count
 *
 *  一个请求过来判断是否有令牌
 */

public class 令牌桶test {
    private int capacity = 100;
    private int count = 0;
    private int rate = 10; //每时间单位放多少个令牌
    private long lastTime = 0L;//上次放的时间戳

    public boolean func() {
        if (count > 0) {
            count--;
            return true;
        }
        return false;
    }

    public void addToken() {
        new Thread(() -> {
            while (true) {
                long currentTimeMillis = System.currentTimeMillis();
                long elapsedTime = currentTimeMillis - lastTime; // 计算时间差
                int add = (int) (elapsedTime * rate / 1000); // 计算应该放置的令牌

                count = Math.min(add + count, capacity);
                lastTime = currentTimeMillis;
                try {
                    Thread.sleep(1000 / rate);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
